package cn.tedu.tmall.admin.mall.handler;

import cn.tedu.tmall.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理运行时异常  运行时的异常太多了.大,
     * 变小 自定义异常 todo
     * @param e
     * @return
     */
//    @ExceptionHandler
//    public JsonResult handleRuntimeException(RuntimeException e){
//        log.error("捕获RuntimeException",e);
//        String message = e.getMessage();
//        return JsonResult.fail(message);
//    }

    public JsonResult handleBeanPropertyBindingResult(BeanPropertyBindingResult e){
        log.error("捕获BeanPropertyBindingResult",e);
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuffer message = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            message.append(fieldError.getDefaultMessage());
        }
        return JsonResult.fail(delete(message));
    }
    /**
     * 兜底 给用户一个相对友好的提示
     * @param throwable
     * @return
     */
    @ExceptionHandler
    public JsonResult handleGlobalException(Throwable throwable){
        log.error("出现异常",throwable);
        String message= "网络不好，请从试...";
        return  JsonResult.fail(message);
    }


        /**
         * 处理 MethodArgumentNotValidException
         */
    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("捕获MethodArgumentNotValidException",e);
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuffer allMessage = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            allMessage.append(fieldError.getDefaultMessage());
            allMessage.append(",");
        }
        return JsonResult.fail(delete(allMessage));
    }


    public String delete(StringBuffer str) {
        StringBuffer stringBuffer = new StringBuffer(str);
        StringBuffer delete = stringBuffer.
                delete(stringBuffer.lastIndexOf(","), stringBuffer.length());
        return delete.toString();
    }


}
